import Vue from 'vue'
//导入路由
import VueRouter from 'vue-router'
// 导入Login.vue 登录组件
import Login from '../components/Login.vue'
//导入Home组件
import Home from '../components/Home.vue'
//导入welcome组件
import Welcome from '../components/Welcome.vue'
//导入用户列表组件
import User from '../components/user/User.vue'
//导入权限列表组件
import Rights from '../components/power/Rights.vue'
//导入角色列表组件
import Roles from '../components/power/Roles.vue'
//导入商品分类组件
import Cate from '../components/goods/Cate.vue'
//导入分类参数组件
import Params from '../components/goods/Params.vue'
//导入商品列表组件
import GoodsList from '../components/goods/List.vue'
//导入添加商品组件
import Add from '../components/goods/Add.vue'
//导入订单管理组件
import Order from '../components/order/Order.vue'
//导入数据报表组件
import Report from '../components/report/Report.vue'
Vue.use(VueRouter)

const routes = [
  //改变根路径指向
  { path: '/', redirect: '/login'},
  { path: '/login', component: Login },
  { path: '/home', component: Home ,
    redirect: '/welcome',
    //welcome是home组件下的子组件
    children:[
      { path: '/welcome', component: Welcome },
      { path: '/users', component: User },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
      { path: '/params', component: Params },
      { path: '/goods', component: GoodsList },
      { path: '/goods/add', component: Add },
      { path: '/orders', component: Order },
      { path: '/reports', component: Report }
    ]
  }
]

const router = new VueRouter({
  //挂载路由规则
  routes
})

//为路由对象添加 beforeEach 导航守卫
router.beforeEach((to,from,next) => {
  //to 表示将要访问的路径 from代表从哪个路径跳转过来  next是一个函数表示放行
  //next() 放行  
  //如果用户访问的登录页直接放行
  if (to.path === '/login') return next()
  //从sessionStorage获取到保存的 token 值
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  //有tokenStr放行  执行了next()方法，才会继续匹配路由，跳到对应的vue界面
  next()
})
export default router
